package com.isyscore.os.metadata.kettle.step;

import com.isyscore.os.metadata.enums.KettleDataFlowNodeType;
import com.isyscore.os.metadata.enums.RequestType;
import com.isyscore.os.metadata.kettle.base.AbstractStep;
import com.isyscore.os.metadata.kettle.base.FlowConfig;
import com.isyscore.os.metadata.kettle.vis.Params;
import com.isyscore.os.metadata.kettle.vis.RestNode;
import com.isyscore.os.metadata.kettle.vis.VisNode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.rest.RestMeta;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author dc
 * @Type RestStep.java
 * @Desc
 * @date 2022/9/13 10:46
 */
public class RestStep extends AbstractStep {

    /**
     * 1.get请求
     * url不带参数 将params参数拼接到url后面
     * url带参数了 判断url信息再拼接params
     * 带了动态参数解析动态参数拼接params
     * <p>
     * 2.post请求
     * 判断param是否为空
     * 如果为空
     * 判断form参数 解析为json传入
     * 判断raw参数 json传入
     * 不为空
     *
     * @param step
     * @param databases
     * @param transMeta
     * @param transGraph
     * @return
     * @throws Exception
     */
    @Override
    public StepMeta decode(VisNode step, List<DatabaseMeta> databases, TransMeta transMeta, FlowConfig transGraph) throws Exception {
        RestNode node = (RestNode) step;
        PluginRegistry registry = PluginRegistry.getInstance();
        PluginInterface sp = registry.findPluginWithId(StepPluginType.class, KettleDataFlowNodeType.Rest.name());
        StepMetaInterface stepMetaInterface = (StepMetaInterface) registry.loadClass(sp);

        RestMeta restMeta = (RestMeta) stepMetaInterface;
        String url = node.getUrl();
        RequestType requestType = node.getRequestType();
        List<Params> formData = node.getFormData();
        List<Params> headers = node.getHeaders();
        String raw = node.getRaw();
        List<Params> params = node.getParams();
        //***************设置body参数填入二选一  raw 与 formData(就是源码的parameters)***************
        if (!RestMeta.HTTP_METHOD_GET.equals(requestType.toString())) {
            if (StringUtils.isNotEmpty(raw)) {
                restMeta.setBodyField(raw);
            }
        }
        //***************设置headers field是值这个值可能是动态的***************
        if (CollectionUtils.isNotEmpty(headers)) {
            String[] headerField = new String[headers.size()];
            String[] headerName = new String[headers.size()];
            for (int i = 0; i < headers.size(); i++) {
                headerField[i] = headers.get(i).getValue();
                headerName[i] = headers.get(i).getKey();
            }
            restMeta.setHeaderField(headerField);
            restMeta.setHeaderName(headerName);
        }

        //***************设置parameters field是值这个值可能是动态的***************
        if (CollectionUtils.isNotEmpty(params)) {
            String[] paramField = new String[params.size()];
            String[] paramName = new String[params.size()];
            for (int i = 0; i < params.size(); i++) {
                paramField[i] = params.get(i).getValue();
                paramName[i] = params.get(i).getKey();
            }
            restMeta.setParameterField(paramField);
            restMeta.setParameterName(paramName);
        }

        //***************url参数设置***************
        restMeta.setUrl(url);
        restMeta.setUrlInField(false);
        //***************现在只支持方法配置死，后面可以让方法动态***************
        restMeta.setDynamicMethod(false);
        restMeta.setMethod(requestType.toString());
        //***************设置结果集***************
        restMeta.setFieldName(node.getResultName());

        StepMeta stepMeta = new StepMeta(KettleDataFlowNodeType.Rest.name(), node.getNodeName(), stepMetaInterface);
        stepMeta.setDraw(true);
        return stepMeta;
    }


    @Override
    public StepMeta after(VisNode step, List<DatabaseMeta> databases, TransMeta transMeta, FlowConfig transGraph) throws Exception {
        return null;
    }

    public static String exp = "\\$\\{([^}]*)\\}";
    public static Pattern regex = Pattern.compile(exp);

    /**
     * 获取表达式中${}中的值
     *
     * @param content
     * @return
     */
    public static String getContentInfo(String content) {
        Matcher matcher = regex.matcher(content);
        StringBuilder sql = new StringBuilder();
        while (matcher.find()) {
            sql.append(matcher.group(1) + ",");
        }
        if (sql.length() > 0) {
            sql.deleteCharAt(sql.length() - 1);
        }
        return sql.toString();
    }
}

